/*******************************************************************************
 * Copyright 2017 Bstek
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License.  You may obtain a copy
 * of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
 * License for the specific language governing permissions and limitations under
 * the License.
 ******************************************************************************/
package com.bstek.ureport.console.res;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bstek.ureport.Utils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.bstek.ureport.console.ServletAction;
import com.bstek.ureport.console.UReportServlet;

/**
 * @author Jacky.gao
 * @since 2016年6月6日
 */
public class ResourceLoaderServletAction implements ServletAction, ApplicationContextAware {
    public static final String URL = "/res";
    private ApplicationContext applicationContext;

    @Override
    public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 构建资源路径
        String contextPath = req.getContextPath();
        String servletUrl = UReportServlet.URL + URL; // 假设URL是静态字段或通过其他方式定义
        String requestUri = req.getRequestURI();
        String token = req.getParameter("token");
        Utils.logToConsole("ResourceLoaderServletAction requestUri:" + requestUri);
        Utils.logToConsole("ResourceLoaderServletAction token:" + token);
        // 计算相对于应用上下文的资源路径
        String resPath = requestUri.substring(contextPath.length() + servletUrl.length() + 1);
        // 定义classpath路径
        String classpathResource = "classpath:" + resPath;
        // 设置正确的MIME类型
        String contentType;
        if (resPath.endsWith(".js")) {
            contentType = "text/javascript";
        } else if (resPath.endsWith(".css")) {
            contentType = "text/css";
        } else if (resPath.endsWith(".png")) {
            contentType = "image/png";
        } else if (resPath.endsWith(".jpg") || resPath.endsWith(".jpeg")) {
            contentType = "image/jpeg";
        } else if (resPath.endsWith(".svg")) {
            contentType = "image/svg+xml";
        } else {
            contentType = "application/octet-stream"; // 默认二进制流
        }
        resp.setContentType(contentType);

        // 获取资源输入流
        InputStream inputStream = applicationContext.getResource(classpathResource).getInputStream();

        // 确保不会有任何其他地方已经调用了getWriter()
        // 注意：这里假设之前没有任何过滤器或其他组件已经获取了Writer
        // 使用try-with-resources语句自动关闭资源
        try (OutputStream outputStream = resp.getOutputStream()) {
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush(); // 确保所有数据都被写出
        } catch (IOException e) {
            throw new ServletException("Failed to write resource to output stream", e);
        } finally {
            IOUtils.closeQuietly(inputStream); // 虽然try-with-resources会自动关闭，但这里是额外的安全措施
        }
    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public String url() {
        return URL;
    }
}
